package com.ruoyi.hov;

import com.ruoyi.common.core.redis.RedisCache;
import com.ruoyi.common.exception.DataNotFindException;
import com.ruoyi.common.utils.StringUtils;
import com.ruoyi.common.utils.spring.SpringUtils;
import com.ruoyi.hov.entity.ClassBindHov;
import com.ruoyi.hov.service.ClassBindHovService;

import java.util.Objects;

/**
 * **********************
 * * Author: XiaShiLong *
 * * Date  : 2021-04-01 *
 * * Time  : 08:49      *
 * * to    : lz&xm      *
 * **********************
 * 类绑定hov工具类
 **/
public class ClassBindHovUtils {

    private static final String REDIS_KEY = "sys_class_bind_hov:";

    /**
     * 设置字典缓存
     *
     * @param classBindHov 绑定对象
     */
    public static void setHovCache(ClassBindHov classBindHov) {
        SpringUtils.getBean(RedisCache.class).setCacheObject(getCacheKey(classBindHov.getClassPath(), classBindHov.getAttributeName()), classBindHov);
    }

    /**
     * 获取属性缓存
     *
     * @param classPath     类全路径
     * @param attributeName 属性名
     * @return classBindHov 绑定对象
     */
    public static ClassBindHov getHovCache(String classPath, String attributeName) {
        Object cacheObj = SpringUtils.getBean(RedisCache.class).getCacheObject(getCacheKey(classPath, attributeName));
        if (Objects.nonNull(cacheObj)) {
            return StringUtils.cast(cacheObj);
        } else {
            ClassBindHov classBindHov = SpringUtils.getBean(ClassBindHovService.class).get(classPath, attributeName);
            if (Objects.nonNull(classBindHov)) {
                setHovCache(classBindHov);
                return classBindHov;
            }
        }
        throw new DataNotFindException("未获取hov!");
    }

    /**
     * 删除key
     *
     * @param classBindHov <see>ClassBindHov</see>
     */
    public static void clearHovCache(ClassBindHov classBindHov) {
        SpringUtils.getBean(RedisCache.class).deleteObject(getCacheKey(classBindHov.getClassPath(), classBindHov.getAttributeName()));
    }

    /**
     * 设置cache key
     *
     * @param classPath     类全路径
     * @param attributeName 属性名
     * @return 缓存键key
     */
    public static String getCacheKey(String classPath, String attributeName) {
        return REDIS_KEY + classPath + ":" + attributeName;
    }

}
